<?php
/**
 * 
 * 保存页面内容
 * @author LeoNing
 *
 */
class SavePage extends Action {
	/*
	 * (non-PHPdoc) @see Action::execute()
	 */
	public function execute($params) {
		$I = check_login ( ADMIN_LOGIN_PAGE );
		$msg = '';
		// 传过来的页面数据
		$page = rqsts ( array ('author', 'cachetime', 'category', 'descripition', 'figure', 'keywords', 'ontopto', 'page_id' => 0, 'page_mode' => 'default', 'page_type', 'source', 'status', 'subcategory', 'title', 'subtitle', 'template_file', 'url', 'summary', 'content' ), true );
		// 缓存时间处理,强制转换为整形
		$page ['cachetime'] = intval ( $page ['cachetime'] );
		// 是否允许评论
		$page ['commentable'] = rqset ( 'commentable' ) ? 1 : 0;
		if (empty ( $page ['page_id'] )) {
			unset ( $page ['page_id'] );
			$page ['create_time'] = time ();
			$page ['create_uid'] = $I->uid; // 创建用户
		}
		$page ['update_uid'] = $I->uid; // 修改用户
		if (! empty ( $page ['url'] )) {
			$page ['url_slug'] = md5 ( $page ['url'] );
		} else {
			$page ['url_slug'] = '';
		}
		$where ['url_slug'] = $page ['url_slug'];
		$where ['status !='] = 'draft';
		$where ['page_id != '] = $page ['page_id'];
		$pM = new WebPageModel ();
		$cM = new WebPageCategory ();
		if ($pM->exist ( $where )) { // url 重复不可保存
			return new JsonView ( array ('success' => false, 'msg' => 'URL重复，请修改URL后再保存.' ) );
		}
		if (empty ( $page ['title'] )) {
			$page ['title'] = '草稿[' . date ( 'Y-m-d H:i' ) . ']';
		}
		if ($page ['status'] == 'deleted') {
			$page ['deleted'] = 1;
			unset ( $page ['status'] );
		}
		$page = apply_filter ( 'on_before_save_page', $page ); // 保存之前
		if (isset ( $page ['status'] ) && $page ['status'] == 'published') {
			$ids = apply_filter ( 'on_publish_page', null, $page ); // 此时可以去掉一些未满足发布条件的网页
			if ($ids === false) {
				return new JsonView ( array ('success' => false, 'msg' => '当前页面未满足发布条件,请检查.' ) );
			}
			$page ['publish_time'] = time ();
		}
		$page ['ontopto'] = empty ( $page ['ontopto'] ) ? '0000-00-00' : $page ['ontopto'];
		
		if (rqset ( 'dr-picture' )) { //需要下载远程图片到本地
			$this->downloadImgs ( $page, $I->uid );
		}
		
		if (rqset ( 'first_figure' ) && empty ( $page ['figure'] )) { //第一张图片做为插图
			$page ['figure'] = $this->getFirstPicASFigure ( $page ['content'] );
		}
		
		$page = $pM->save ( $page );
		if ($page) {
			if (empty ( $page ['url'] ) || preg_match ( '#\{(id|Y|y|m|d|R|uid|M|t|cp|n|p|P)\}#', $page ['url'] )) { // 只要URL为空，则根据cate中子页面的URL规则生成
				$page1 ['url'] = $cM->generateUrl ( $page ['category'], $page );
				$page1 ['url_slug'] = md5 ( $page1 ['url'] );
				$where ['url_slug'] = $page1 ['url_slug'];
				if ($pM->exist ( $where )) { // url 重复,提醒用户修改
					$page1 ['status'] = 'draft';
					$msg = '页面的URL重复，请定义URL后再保存。';
				}
				$page1 = $pM->update ( $page1, $page ['page_id'] );
				if ($page1) {
					$page ['url'] = $page1 ['url'];
					$page ['status'] = $page1 ['status'];
				} else {
					$msg = '自动生成URL出错了，请自定义URL后再保存。';
				}
			}
			$this->setFlags ( $page ['page_id'] ); // 处理标记
			$this->setTags ( $page ['page_id'] ); // 处理标签
			fire ( 'on_after_save_page', $page ); // 保存之后
			$data ['success'] = true;
			$data ['page_id'] = $page ['page_id'];
		} else {
			$data ['success'] = false;
			$msg = "在保存页面时发生了错误:" . $pM->last_error_msg ();
		}
		$data ['msg'] = $msg;
		$data ['url'] = $page ['url'];
		$data ['figure'] = $page ['figure'];
		$data ['save_figure'] = the_safe_url($page ['figure']);
		$data ['content'] = $page ['content'];
		return new JsonView ( $data );
	}
	// 保存页面的标签
	private function setTags($page_id) {
		$tags = rqst ( 'tags' );
		if (! empty ( $tags )) {
			$ptM = new WebPageTagModel ();
			$ptM->setTags ( $page_id, $tags );
		}
	}
	// 保存页面的标记
	private function setFlags($page_id) {
		$flags = rqst ( 'flags' );
		if (! empty ( $flags )) {
			$ptM = new WebPageTagModel ();
			$ptM->setFlags ( $page_id, $flags );
		}
	}
	//下载远程图片
	private function downloadImgs(&$page, $uid) {
		$content = $page ['content'];
		$pattern = '#<img.+?src\s*=\s*["\'](https?://.*?)["\'][^>]*>#mi';
		if (preg_match_all ( $pattern, $content, $matches, PREG_SET_ORDER )) {
			$alts = array ();
			$imgs = array ();
			foreach ( $matches as $key => $val ) {
				$imgurl = $val [1];
				if (! preg_match ( '#^https?://.+#i', $imgurl )) {
					continue;
				} else if (preg_match ( '#^https?://.+#i', BASE_URL ) && stripos ( $imgurl, BASE_URL ) == 0) {
					continue;
				} else if (! empty ( $_SERVER ['HTTP_HOST'] ) && preg_match ( '#https?://' . $_SERVER ['HTTP_HOST'] . '.*#i', $imgurl )) {
					continue;
				}
				if (preg_match ( '#alt=["\'](.*?)["\']#i', $val [0], $ms )) {
					$alts [$imgurl] = $ms [1];
				}
				$imgs [] = $imgurl;
			}
			$dimgs = ImageUtil::downloadRemotePic ( $imgs );
			if ($dimgs) {
				$waM = new WebAttachmentModel ();
				$data ['create_uid'] = $uid;
				$data ['create_time'] = time ();
				foreach ( $dimgs as $key => $img ) {
					if (isset ( $alts [$key] )) {
						$img ['name'] = $img ['alt_text'] = $alts [$key];
					}
					$img = array_merge ( $data, $img );
					$waM->insert ( $img );
					$content = str_replace ( $key, the_safe_url ( $img ['url'] ), $content );
				}
				$page ['content'] = $content;
			}
		}
	}
	//取第一张图片为插图
	private function getFirstPicASFigure($content) {
		$pattern = '#<img.+?src\s*=\s*["\'](.*?)["\'][^>]*>#mi';
		if (preg_match_all ( $pattern, $content, $matches, PREG_SET_ORDER )) {
			$url = $matches [0] [1];
			if (preg_match ( '/^http.+/', $url )) {
				return $url;
			} else {
				return trim ( $url, '/' );
			}
		}
		return '';
	}
}